package services

import (
	"errors"
	"simple-crm/models"
	"gorm.io/gorm"
)

type PermissionService struct {
	db *gorm.DB
}

func NewPermissionService(db *gorm.DB) *PermissionService {
	return &PermissionService{db: db}
}

// 检查用户是否有指定权限
func (s *PermissionService) HasPermission(userID uint, permission string) bool {
	var count int64
	s.db.Table("users").
		Joins("JOIN user_roles ON users.id = user_roles.user_id").
		Joins("JOIN roles ON user_roles.role_id = roles.id").
		Joins("JOIN role_permissions ON roles.id = role_permissions.role_id").
		Joins("JOIN permissions ON role_permissions.permission_id = permissions.id").
		Where("users.id = ? AND permissions.name = ? AND users.status = 'active' AND roles.status = 'active'", userID, permission).
		Count(&count)
	
	return count > 0
}

// 获取用户所有权限
func (s *PermissionService) GetUserPermissions(userID uint) ([]models.Permission, error) {
	var permissions []models.Permission
	err := s.db.Table("permissions").
		Joins("JOIN role_permissions ON permissions.id = role_permissions.permission_id").
		Joins("JOIN roles ON role_permissions.role_id = roles.id").
		Joins("JOIN user_roles ON roles.id = user_roles.role_id").
		Where("user_roles.user_id = ? AND roles.status = 'active'", userID).
		Distinct().
		Find(&permissions).Error
	
	return permissions, err
}

// 获取用户角色
func (s *PermissionService) GetUserRoles(userID uint) ([]models.Role, error) {
	var roles []models.Role
	err := s.db.Table("roles").
		Joins("JOIN user_roles ON roles.id = user_roles.role_id").
		Where("user_roles.user_id = ? AND roles.status = 'active'", userID).
		Find(&roles).Error
	
	return roles, err
}

// 分配角色给用户
func (s *PermissionService) AssignRole(userID, roleID, assignedBy uint) error {
	// 检查角色是否存在
	var role models.Role
	if err := s.db.First(&role, roleID).Error; err != nil {
		return errors.New("角色不存在")
	}
	
	// 检查是否已经分配
	var count int64
	s.db.Model(&models.UserRole{}).Where("user_id = ? AND role_id = ?", userID, roleID).Count(&count)
	if count > 0 {
		return errors.New("用户已拥有该角色")
	}
	
	// 创建用户角色关联
	userRole := models.UserRole{
		UserID:     userID,
		RoleID:     roleID,
		AssignedBy: &assignedBy,
	}
	
	return s.db.Create(&userRole).Error
}

// 移除用户角色
func (s *PermissionService) RemoveRole(userID, roleID uint) error {
	return s.db.Where("user_id = ? AND role_id = ?", userID, roleID).Delete(&models.UserRole{}).Error
}

// 记录操作日志
func (s *PermissionService) LogOperation(userID uint, action, resource string, resourceID *uint, details, ipAddress, userAgent string) {
	log := models.OperationLog{
		UserID:     userID,
		Action:     action,
		Resource:   resource,
		ResourceID: resourceID,
		Details:    details,
		IPAddress:  ipAddress,
		UserAgent:  userAgent,
	}
	
	s.db.Create(&log)
}